# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
ISODATEFORMAT = '%Y-%m-%d'


class solar_terms(osv.osv):
    _name = 'solar.terms'
    _rec_name = 'season_name'
    _columns = {
        'season': fields.char(u'节气编号'),
        'season_name': fields.char(u'节气名称'),
    }


class product_template(osv.osv):
    _inherit = 'product.template'

    def create(self, cr, uid, vals, context=None):
        """1.成本价必须进行维护,必须不为零 2.分类也不能是 最上层的分类"""
        #暂时不判断
        #if vals.get('standard_price', 0) == 0:
        #    raise osv.except_osv(u'错误', u"成本价不能为零！")
        model_data_obj = self.pool.get('ir.model.data')
        categ_id = model_data_obj.xmlid_to_res_id(cr, 1, 'product.product_category_all')
        if vals.get("categ_id") == categ_id:
            raise osv.except_osv(u'错误', u"分类不能为全部，必须选择其他的！")
        if vals.get('categ_id') and (vals.get('default_code') == '/' or not vals.get('default_code')):
            category_obj = self.pool.get('product.category')
            categ_id_code_list = []
            categ_id = vals.get('categ_id')
            sequence = self.pool.get('ir.sequence').get(cr, uid, 'product.product', context=context)
            while categ_id:
                categ = category_obj.browse(cr, uid, categ_id , context=context)
                categ_id_code_list.append(categ.code or '')
                categ_id = categ.parent_id and categ.parent_id.id
            categ_id_code_list.reverse()
            vals.update({'default_code': "%s%s" % (''.join(categ_id_code_list),sequence)})
        if vals.get('list_price', 'default_val') != 'default_val':
            if vals.get('list_price') < vals.get('standard_price'):
                raise osv.except_osv(u'错误', u"销售价不能低于成本价！")
        return super(product_template, self).create(cr, uid, vals, context=context)

    def write(self, cr, uid, ids, vals, context=None):
        if vals.get('standard_price') == 0:
            raise osv.except_osv(u'错误', u"成本价不能为零！")
        for template_row in self.browse(cr, uid, ids, context=context):
            if vals.get('standard_price'):
                standard_price = vals.get('standard_price')
            else:
                standard_price = template_row.standard_price
            if vals.get('list_price', 'default_val') != 'default_val':
                list_price = vals.get('list_price')
            else:
                list_price = template_row.list_price
            # if list_price < standard_price:
            #     raise osv.except_osv(u'错误', u"销售价不能低于成本价！")
        model_data_obj = self.pool.get('ir.model.data')
        categ_id = model_data_obj.xmlid_to_res_id(cr, 1, 'product.product_category_all')
        if vals.get("categ_id") == categ_id:
            raise osv.except_osv(u'错误', u"分类不能为全部，必须选择其他的！")
        # 更改产品名称，同时更改规格产品的name_template
        if vals.get('name'):
            product_product_obj = self.pool.get('product.product')
            sql = "UPDATE product_product SET name_template = %s WHERE product_tmpl_id in %s;UPDATE product_template SET name = %s WHERE id in %s;"
            cr.execute(sql, (vals.get('name'), tuple(ids), vals.get('name'), tuple(ids)))
        return super(product_template, self).write(cr, uid, ids, vals, context=context)

    def action_view_purchases(self, cr, uid, ids, context=None):
        products = self._get_products(cr, uid, ids, context=context)
        result = self._get_act_window_dict(cr, uid, 'purchase.action_purchase_line_product_tree', context=context)
        result['domain'] = "[('product_id','in',[" + ','.join(map(str, products)) + "]),('state','!=','cancel')]"
        return result

    def _get_conversion_count(self, cr, uid, ids, field_name, arg, context=None):
        move_obj = self.pool.get('stock.move')
        res = {
            product_id: move_obj.search_count(cr, uid,
                                              [('product_id', '=', product_id), ('state', '!=', 'done'),
                                               ('raw_material_change_id', '!=', False)], context=context)
            for product_id in ids
        }
        for id in ids:
            product_out_num = sum([line_obj.get('product_qty') for line_obj in
                 move_obj.search_read(cr, uid, [('product_id', '=', id), ('state', '=', 'done'),
                                      ('raw_material_change_id', '!=', False)], ['product_qty'], context=context)])
            product_in_num = sum([line_obj.get('product_qty') for line_obj in
                                   move_obj.search_read(cr, uid, [('product_id', '=', id), ('state', '=', 'done'),
                                                        ('change_id', '!=', False)], ['product_qty'],
                                                        context=context)])
            res[id] = product_out_num - product_in_num
        return res

    def action_view_conversion_count(self, cr, uid, ids, context=None):
        package_obj = self.pool.get('product.package')
        move_obj = self.pool.get('stock.move')
        move_ids = move_obj.search(cr, uid, [('product_id', '=', ids), ('state', '=', 'done'),
                                             '|', ('raw_material_change_id', '!=', False), ('change_id', '!=', False)],
                                   context=context)
        return package_obj.return_action(cr, uid, False, 'stock', 'action_move_form2', 'view_move_tree_receipt_picking',
                                         return_type='tree', domain=[('id', 'in', move_ids)], context=context)

    _columns = {
        'prod_model': fields.char(u'产品型号'),
        'prod_brand': fields.char(u'产品品牌'),
        'prod_spec': fields.char(u'型号备注'),
        'prod_ingredient': fields.char(u'产品成分'),
        'prod_packaging': fields.char(u'产品包装'),
        'price_floor': fields.float(u'最低销售价'),
        'price_vip': fields.float(u'VIP价格'),
        'price_group': fields.float(u'团购价'),
        'price_preferential': fields.float(u'优惠价'),
        'prod_points': fields.float(u'产品积分'),
        'least_order_num': fields.integer(u'最少订购数'),
        'publish_memo': fields.char(u'发行备注'),
        'on_sale_date': fields.date(u'销售起始时间'),
        'prod_comment': fields.html(u'产品说明'),
        'stock_memo': fields.text(u'库存备注'),
        'max_provide_cycle': fields.integer(u'最长供货周期'),
        'min_provide_cycle': fields.integer(u'最短供货周期'),
        'is_spot': fields.boolean(u'是否现货'),
        'season_ids':fields.many2many('solar.terms','product_season_rel','product_id','soler_terms_id',string='推荐节气'),
        'deduct_type': fields.char(u'提成类型'),
        'pcs_qty': fields.integer(u'装箱数'),
        'description': fields.text(string=u'描述', translate=False),
        'price_market': fields.float(u'市场价'),
        'conversion_count': fields.function(_get_conversion_count, string='消耗数量', type='integer'),
    }
    _defaults = {
        'type': 'product'
    }


class product_product(osv.Model):
    _name = 'product.product'
    _inherit = 'product.product'

    def name_get(self, cr, user, ids, context=None):
        """根据不同的情况 进行分类的 显示prodcut的name """
        if not context.get('separate_display_product_id'):
            res = super(product_product, self).name_get(cr, user, ids, context=context)
        else:
            res = [(product.id, product.name) for product in self.browse(cr, user, ids, context=context)]
        return res

    def _purchase_count(self, cr, uid, ids, field_name, arg, context=None):
        Purchase = self.pool['purchase.order']
        res = {
            product_id: Purchase.search_count(cr, uid, [('order_line.product_id', '=', product_id),('state','!=','cancel')], context=context)
            for product_id in ids
        }
        for id in ids:
            purchase_order_line_ids = self.pool.get("purchase.order.line").search(cr, uid, [('product_id', '=', id),('state','!=','cancel')], context=context)
            res[id] = sum([line_obj.product_qty for line_obj in self.pool.get("purchase.order.line").browse(cr, uid, purchase_order_line_ids, context=context)])
        return res

    def get_product_location_available_qty(self, cr, uid, product_ids, so_id=False, context=None):
        """根据参数 产品的ids 和库位的信息 查找到 对应库位的产品的数量 返回结果是 {'produc_id':'qty'} de 形式"""
        res = {}
        if product_ids:
            if so_id:
                reservation_str = '(reservation_id is NULL or reservation_id=-1 and so_id=%s)' % so_id
            else:
                reservation_str = 'reservation_id is NULL'
            cr.execute("""SELECT product_id AS product_id,
                          sum(qty) as qty,
                          prod_spec as prod_spec,
                          location_id as location_id
                          from stock_quant where product_id in %s and  %s
                          group by product_id,prod_spec,location_id
                          """ % (str(product_ids).replace('[', '(').replace(']', ')'), reservation_str))
            available_qty = cr.dictfetchall()
            map(lambda x: res.setdefault((x.get('product_id'), x.get('prod_spec', False), x.get('location_id')), x.get('qty')), available_qty)
        return res

    def action_view_purchases(self, cr, uid, ids, context=None):
        if isinstance(ids, (int, long)):
            ids = [ids]
        result = self.pool['product.template']._get_act_window_dict(cr, uid,
                                                                    'purchase.action_purchase_line_product_tree',
                                                                    context=context)
        result['domain'] = "[('product_id','in',[" + ','.join(map(str, ids)) + "]),('state','!=','cancel')]"
        return result

    def _get_conversion_count(self, cr, uid, ids, field_name, arg, context=None):
        move_obj = self.pool.get('stock.move')
        res = {
            product_id: move_obj.search_count(cr, uid,
                                              [('product_id', '=', product_id), ('state', '!=', 'done'),
                                               ('raw_material_change_id', '!=', False)], context=context)
            for product_id in ids
        }
        for id in ids:
            product_out_num = sum([line_obj.get('product_qty') for line_obj in
                 move_obj.search_read(cr, uid, [('product_id', '=', id), ('state', '=', 'done'),
                                      ('raw_material_change_id', '!=', False)], ['product_qty'], context=context)])
            product_in_num = sum([line_obj.get('product_qty') for line_obj in
                                   move_obj.search_read(cr, uid, [('product_id', '=', id), ('state', '=', 'done'),
                                                        ('change_id', '!=', False)], ['product_qty'],
                                                        context=context)])
            res[id] = product_out_num - product_in_num
        return res

    def action_view_conversion_count(self, cr, uid, ids, context=None):
        package_obj = self.pool.get('product.package')
        move_obj = self.pool.get('stock.move')
        move_ids = move_obj.search(cr, uid, [('product_id', '=', ids), ('state', '=', 'done'),
                                             '|', ('raw_material_change_id', '!=', False), ('change_id', '!=', False)],
                                   context=context)
        return package_obj.return_action(cr, uid, False, 'stock', 'action_move_form2', 'view_move_tree_receipt_picking',
                                         return_type='tree', domain=[('id', 'in', move_ids)], context=context)

    _columns = {
        # 'state': fields.selection([(u'draft', u'draft'), (u'confirm', u'confirm')], string=u"状态"),
        'sale_order_line_ids': fields.one2many("sale.order.line", "product_id",domain=[('state','!=','cancel')], string="销售订单明细"),
        'purchase_order_line_ids': fields.one2many("purchase.order.line", "product_id",domain=[('state','!=','cancel')], string="采购订单明细"),
        'purchase_count': fields.function(_purchase_count, string='# Purchases', type='integer'),
        'is_financial_confirm': fields.boolean(u'是否需要财务确认'),
        'conversion_count': fields.function(_get_conversion_count, string='消耗数量', type='integer'),
    }

class MergeProductAutomatic(osv.TransientModel):
    _inherit = 'base.product.merge.automatic.wizard'
    _defaults = {
        'product_from': lambda self, cr, uid, context=None:
                        self.pool.get('product.product').search(cr, uid,[('id', 'in',context.get('active_ids'))],order='create_date',context=context)[0],
        'product_to': lambda self, cr, uid, context=None:
                            self.pool.get('product.product').search(cr, uid, [('id', 'in',context.get('active_ids'))],
                                                    order = 'create_date', context = context)[1],
    }


    def fields_view_get(self, cr, uid, view_id=None, view_type='form',
                        context=None, toolbar=False, submenu=False):
        # 创建假单前，要进行判断，已有的假单销售订单，不允许创建。
        if context is None:
            context = {}
        res = super(MergeProductAutomatic, self).fields_view_get(
            cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        if context.get('active_model', '') == 'product.product':
            if len(context['active_ids']) !=2:
                raise osv.except_osv(_('Warning!'),
                                         u'请选择两个产品进行合并' )
        return res


